package com.jackrain.nea.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.schema.Column;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ShiroSessionUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.security.SecurityWebUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author lzm
 * @date 2017-11-4
 */
@Slf4j
@RestController
@Api(value = "ImportController", description = "数据导入")
public class ImportController {
    private static final int EXCEL_MAX_ROW_COUNT = 65535;    //excel最大行数
    /**
     * 下载导入模板
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(path = "/p/cs/downloadImportTemplate",method = RequestMethod.GET)
    public JSONObject export(HttpServletRequest request,
                             @RequestParam(value = "searchdata", required = true) String searchdata) throws Exception {
//        User user = (User) ShiroSessionUtil.getAttribute("user");
        User user = SecurityWebUtils.getUser("root");
        QuerySessionImpl session = new QuerySessionImpl(request);
        TableManager tm = session.getTableManager();

        JSONObject jo= JSON.parseObject(searchdata);
        Table table = null;
        int tableid=jo.getIntValue("tableid") ;

        if(tableid>0&&table==null) {
            table = tm.getTable(tableid);
        }
        if(jo.getString("table")!=null&&table==null) {
            table = tm.getTable(jo.getString("table"));
        }
        if(table==null) {
            throw  new NDSException("tablenull");
        }

        String location = ResourceUtils.getURL("classpath:").getPath();
        location = location + "import" + File.separator + user.getId() + File.separator;

        File svrDir = new File(location);
        if (!svrDir.isDirectory()) {
            svrDir.mkdirs();
        }
        String fullFileName = location + table.getName() + ".xls";

        try {
            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet(table.getName());

            sheet.createFreezePane(0,1,0,1);
//            CellStyle headStyle = getStyle(wb,true,false,"STRING");
            ArrayList columns = table.getModifiableColumns(Table.ADD); // table.getColumns(new int[]{Column.ADD}, false,-1);
            Row titleRow;
            Cell cell;
            titleRow = sheet.createRow(0);
            for (int i = 0; i < columns.size(); i++) {
                Column col = (Column) columns.get(i);
                cell = titleRow.createCell((short) i);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellStyle(getStyleByColumn(wb,sheet, col, i, session));
                String colDisplayName = col.getDescription(session.getLocale());
                cell.setCellValue(colDisplayName);
                sheet.setColumnWidth((short)i,(colDisplayName.getBytes().length*256*2));
            }
            FileOutputStream fileOut = new FileOutputStream(fullFileName);
            wb.write(fileOut);
            fileOut.close();
        }
        catch (Exception e){
            log.error("导入失败:" + location + File.separator + table.getName(), e);
            throw new NDSException(e.getMessage(),e);
        }

        ValueHolder valueHolder = new ValueHolder();
        valueHolder.put("code",0);
        valueHolder.put("data",fullFileName);
        return valueHolder.toJSONObject();
    }

    private CellStyle getStyleByColumn(Workbook wb, Sheet sheet, Column column, int columnIndex, QuerySessionImpl session){
        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 10);
        font.setFontName("宋体");

        font.setColor(HSSFColor.DARK_BLUE.index);
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

        if (!column.isNullable()) {
            font.setColor(HSSFColor.RED.index);
        }
        // Fonts are set into a style so create a new one to use.
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        int columnType =column.getType();
        DataFormat format = wb.createDataFormat();
        if(columnType == Column.STRING){
            style.setDataFormat(format.getFormat("text"));
        }else if(columnType == Column.NUMBER){
            style.setDataFormat(format.getFormat("General"));
        }


        CellRangeAddressList regions = new CellRangeAddressList(0, EXCEL_MAX_ROW_COUNT,columnIndex, columnIndex);
        //TODO:字段类型没做处理（number/date/dateNumber都没有类型约束）
        int displayType = column.getDisplaySetting().getObjectType();
        if(displayType >= 3 && displayType <= 5){
            List<String> keys= column.getValues(session.getLocale()).valueList();
            DVConstraint constraint =DVConstraint.createExplicitListConstraint(keys.toArray(new String[0]));
            HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
            sheet.addValidationData(dataValidate);
//            //对应的提示
//            constraint = DVConstraint.createCustomFormulaConstraint("BB1");
//            HSSFDataValidation data_validation_view = new HSSFDataValidation(regions,constraint);
//            data_validation_view.createPromptBox("可选值：", column.getValues(session.getLocale()).toString());
//            sheet.addValidationData(data_validation_view);
        }
        return style;
    }
}
